package com.tiantian.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tiantian.bean.PageBean;
import com.tiantian.dao.BusinessCapitalChangesDetailsRepository;
import com.tiantian.dao.BusinessUsersRepository;
import com.tiantian.dao.BuyerCapitalChangesDetailsRepository;
import com.tiantian.dao.BuyersUsersRepository;
import com.tiantian.dao.OrdersStepsRepository;
import com.tiantian.dao.OrdersstepattachRepository;
import com.tiantian.dao.PlatformCapitalChangesRepository;
import com.tiantian.dao.PlatforminformationRepository;
import com.tiantian.dao.TasksOrdersRepository;
import com.tiantian.datajpa.service.impl.GenericServiceImpl;
import com.tiantian.domain.Businesscapitalchangesdetails;
import com.tiantian.domain.BusinesscapitalchangesdetailsId;
import com.tiantian.domain.Businessusers;
import com.tiantian.domain.Buyercapitalchangesdetails;
import com.tiantian.domain.BuyercapitalchangesdetailsId;
import com.tiantian.domain.Buyersusers;
import com.tiantian.domain.Ordersstepattach;
import com.tiantian.domain.Orderssteps;
import com.tiantian.domain.Platformcapitalchanges;
import com.tiantian.domain.Platforminformation;
import com.tiantian.domain.Tasksorders;
import com.tiantian.ret.Result;
import com.tiantian.service.TasksOrdersService;
import com.tiantian.util.CommonConstant.QueryType;
import com.tiantian.util.ConditionResult;

/**
 * @description 审核管理
 */
@Service
@Transactional
public class TasksOrdersServiceImpl extends GenericServiceImpl<Tasksorders, String> implements TasksOrdersService {
	private TasksOrdersRepository repository;
	@Autowired
	private OrdersStepsRepository ordersStepsRepository;
	@Autowired
	private BusinessCapitalChangesDetailsRepository businessCapitalChangesDetailsRepository;
	@Autowired
	private BuyerCapitalChangesDetailsRepository buyerCapitalChangesDetailsRepository;
	@Autowired
	private PlatformCapitalChangesRepository platformCapitalChangesRepository;
	@Autowired
	private BuyersUsersRepository buyersUsersRepository;
	@Autowired
	private BusinessUsersRepository businessUsersRepository;
	@Autowired
	private PlatforminformationRepository platforminformationRepository;
	@Autowired
	private OrdersstepattachRepository ordersstepattachRepository;

	@Autowired
	public void setRepository(TasksOrdersRepository repository) {
		super.setGenericDAO(repository);
		this.repository = repository;
	}

	public List<Map<String, Object>> list(Map<String, String> params, PageBean pageBean) {
		ConditionResult conditionResult = getQueryCondition(params, QueryType.LIST);
		List<Map<String, Object>> ret = repository.queryHumpListMapBySql(conditionResult.getSql(), pageBean.getStartIndex(), pageBean.getPageSize(),
				conditionResult.getParams());
		conditionResult = getQueryCondition(params, QueryType.COUNT);
		pageBean.setTotal(repository.queryCountBySql(conditionResult.getSql(), conditionResult.getParams()));
		return ret;
	}

	private ConditionResult getQueryCondition(Map<String, String> searchMap, QueryType type) {
		StringBuilder sql = new StringBuilder();
		Map<String, Object> params = new HashMap<String, Object>();

		switch (type) {
		case LIST:
			sql.append(" select t.*,ti.PlatformID,ti.TerminalID,tc.TaskTypeName,b.StoreName,u.AppealsStatus ");
			break;
		case COUNT:
			sql.append(" select count(1)");
			break;
		default:
			break;
		}
		sql.append("  from TasksOrders t left join TaskInformation ti on t.TaskID=ti.TaskID ");
		sql.append("  	LEFT JOIN UserComplaints u on u.OrderID = t.OrderID ");
		sql.append("    LEFT JOIN TasksCombinationType tc on tc.Task2TypeId=t.OrderTypeID ");
		sql.append("    LEFT JOIN  BusinessStore b on b.StoreNo=ti.StoreNo and b.BusinessUserID=ti.BusinessUserID ");
		sql.append("   	where 1=1");
		if (searchMap != null) {
			// 订单id
			String orderid = searchMap.get("orderid");
			if (StringUtils.isNotBlank(orderid)) {
				sql.append(" and t.orderid like :orderid ");
				params.put("orderid", "%" + orderid.trim() + "%");
			}

			String selectOrderid = searchMap.get("selectOrderid");
			if (StringUtils.isNotBlank(selectOrderid)) {
				sql.append(" and t.orderid = :orderid ");
				params.put("orderid", selectOrderid);
			}
			// 任务ID类型
			String taskid = searchMap.get("taskid");
			if (StringUtils.isNotBlank(taskid)) {
				sql.append(" and t.taskid like :taskid ");
				params.put("taskid", "%" + taskid.trim() + "%");
			}
			// 买手生菜id
			String buyersuserid = searchMap.get("buyersuserid");
			if (StringUtils.isNotBlank(buyersuserid)) {
				sql.append(" and t.buyersuserid like :buyersuserid ");
				params.put("buyersuserid", "%" + buyersuserid.trim() + "%");
			}
			// 平台类型
			String platformid = searchMap.get("platformid");
			if (StringUtils.isNotBlank(platformid)) {
				sql.append(" and ti.platformid=:platformid ");
				params.put("platformid", platformid.trim());
			}

			// 店铺名称
			String storename = searchMap.get("storename");
			if (StringUtils.isNotBlank(storename)) {
				sql.append(" and b.storename like :storename ");
				params.put("storename", "%" + storename.trim() + "%");
			}

			// 终端类型
			String terminalid = searchMap.get("terminalid");
			if (StringUtils.isNotBlank(terminalid)) {
				sql.append(" and ti.terminalid = :terminalid ");
				params.put("terminalid", Integer.valueOf(terminalid.trim()));
			}

			// 订单类型
			String orderTypeID = searchMap.get("orderTypeId");
			if (StringUtils.isNotBlank(orderTypeID)) {
				sql.append(" and t.orderTypeId = :orderTypeId ");
				params.put("orderTypeId", orderTypeID.trim());
			}

			// 订单状态
			String orderstatus = searchMap.get("orderstatus");
			if (StringUtils.isNotBlank(orderstatus)) {
				sql.append(" and t.orderstatus = :orderstatus ");
				params.put("orderstatus", orderstatus.trim());
			} else {
				sql.append(" and (t.orderstatus != 1 and t.orderstatus != 8)");
			}

			// 买手账号
			String platformaccount = searchMap.get("platformaccount");
			if (StringUtils.isNotBlank(storename)) {
				sql.append(" and t.platformaccount like :platformaccount ");
				params.put("platformaccount", "%" + platformaccount.trim() + "%");
			}

			// 申诉状态
			String appealsstatus = searchMap.get("appealsstatus");
			if (StringUtils.isNotBlank(appealsstatus)) {
				if (StringUtils.equals("-1", appealsstatus)) {
					sql.append(" and u.appealsstatus is null ");
				} else {
					sql.append(" and u.appealsstatus = :appealsstatus ");
					params.put("appealsstatus", appealsstatus.trim());
				}

			}
			// 开始时间
			String starttime = searchMap.get("starttime");
			if (StringUtils.isNotBlank(starttime)) {
				sql.append(" and t.OrdersTime>=:starttime ");
				params.put("starttime", starttime.trim());
			}
			// 结束时间
			String endtime = searchMap.get("endtime");
			if (StringUtils.isNotBlank(endtime)) {
				sql.append(" and t.OrdersTime<=:endtime ");
				params.put("endtime", endtime.trim());
			}
		}
		if (type == QueryType.LIST) {
			sql.append(" order by t.OrdersTime desc");
		}
		return new ConditionResult(sql.toString(), params);

	}

	public List<Orderssteps> getOrdersSteps(String id) {
		String sql = "select * from OrdersSteps t where t.OrderID=:orderid order by t.OrderStepType";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderid", id);
		return ordersStepsRepository.queryListBySql(sql, params, Orderssteps.class);
	}

	public List<Map<String, Object>> getOrderReport(Map<String, String> params, PageBean pageBean) {
		ConditionResult conditionResult = getQueryCondition(params, QueryType.COUNT);
		pageBean.setTotal(repository.queryCountBySql(conditionResult.getSql(), conditionResult.getParams()));
		conditionResult = getQueryCondition(params, QueryType.LIST);
		List<Map<String, Object>> ret = repository.queryHumpListMapBySql(conditionResult.getSql(), pageBean.getStartIndex(), pageBean.getTotal()
				.intValue(), conditionResult.getParams());
		return ret;
	}

	public Result<Object> cancelOrder(String orderId) {
		// 修改订单状态
		Tasksorders tasksorders = repository.findOne(orderId);
		if (tasksorders == null) {
			return new Result<>(false, "修改的订单不存在");
		}
		if (tasksorders.getOrderStatus() == 7) {
			return new Result<>(false, "无法撤销已完成订单");
		}
		if (tasksorders.getOrderStatus() == 8) {
			return new Result<>(false, "改订单已经撤销");
		}
		tasksorders.setOrderStatus(8);
		repository.save(tasksorders);

		// 资金回流
		List<Businesscapitalchangesdetails> businessDetails = businessCapitalChangesDetailsRepository.findByAssociateOrderFormId(orderId);
		if (businessDetails != null) {
			for (Businesscapitalchangesdetails businessDetail : businessDetails) {
				if (businessDetail.getChangeReasonId() == null) {
					continue;
				}

				if (Integer.valueOf(businessDetail.getChangeReasonId()) < 5 || Integer.valueOf(businessDetail.getChangeReasonId()) > 20) {
					continue;
				}
				Businessusers businessusers = businessUsersRepository.findOne(businessDetail.getId().getBusinessUserId());
				if (businessusers == null) {
					continue;
				}
				Businesscapitalchangesdetails changeDetil = copy(businessDetail);
				if (businessDetail.getChangeAccount() == '0') {// 基本账户
					if (businessDetail.getPaymentsDirection() == '0') {// 支出
						businessusers.setBasicAccount(businessusers.getBasicAccount().add(businessDetail.getMoneyAmount()));
						changeDetil.setChangeBalance(businessusers.getBasicAccount());
					} else {// 收入
						businessusers.setBasicAccount(businessusers.getBasicAccount().subtract(businessDetail.getMoneyAmount()));
						changeDetil.setChangeBalance(businessusers.getBasicAccount());
					}
				} else {// 冻结账户
					if (businessDetail.getPaymentsDirection() == '0') {// 支出
						businessusers.setFreezeAccount(businessusers.getFreezeAccount().add(businessDetail.getMoneyAmount()));
						changeDetil.setChangeBalance(businessusers.getFreezeAccount());
					} else {// 收入
						businessusers.setFreezeAccount(businessusers.getFreezeAccount().subtract(businessDetail.getMoneyAmount()));
						changeDetil.setChangeBalance(businessusers.getFreezeAccount());
					}
				}
				changeDetil.setChangeReasonId(String.valueOf((Integer.valueOf(businessDetail.getChangeReasonId()) + 30)));
				businessUsersRepository.save(businessusers);
				businessCapitalChangesDetailsRepository.save(changeDetil);
			}
		}
		// 买手
		List<Buyercapitalchangesdetails> buyerDatails = buyerCapitalChangesDetailsRepository.findByAssociateOrderFormId(orderId);
		if (buyerDatails != null) {
			for (Buyercapitalchangesdetails buyerDatail : buyerDatails) {
				if (buyerDatail.getChangeReasonId() == null) {
					continue;
				}

				if (Integer.valueOf(buyerDatail.getChangeReasonId()) < 5 || Integer.valueOf(buyerDatail.getChangeReasonId()) > 20) {
					continue;
				}

				Buyersusers buyersusers = buyersUsersRepository.findOne(buyerDatail.getId().getBuyerUserId());
				if (buyersusers == null) {
					continue;
				}
				Buyercapitalchangesdetails changeDetil = copy(buyerDatail);
				if (buyerDatail.getChangeAccount() == '0') {// 基本账户
					if (buyerDatail.getPaymentsDirection() == '0') {// 支出
						buyersusers.setBasicAccount(buyersusers.getBasicAccount().add(buyerDatail.getMoneyAmount()));
						changeDetil.setChangeBalance(buyersusers.getBasicAccount());
					} else {// 收入
						buyersusers.setBasicAccount(buyersusers.getBasicAccount().subtract(buyerDatail.getMoneyAmount()));
						changeDetil.setChangeBalance(buyersusers.getBasicAccount());
					}
				} else {// 生财账户
					if (buyerDatail.getPaymentsDirection() == '0') {// 支出
						buyersusers.setMakingMoneyAccount(buyersusers.getMakingMoneyAccount().add(buyerDatail.getMoneyAmount()));
						changeDetil.setChangeBalance(buyersusers.getMakingMoneyAccount());
					} else {// 收入
						buyersusers.setMakingMoneyAccount(buyersusers.getMakingMoneyAccount().subtract(buyerDatail.getMoneyAmount()));
						changeDetil.setChangeBalance(buyersusers.getMakingMoneyAccount());
					}
				}
				changeDetil.setChangeReasonId(String.valueOf((Integer.valueOf(buyerDatail.getChangeReasonId()) + 30)));
				buyerCapitalChangesDetailsRepository.save(changeDetil);
				buyersUsersRepository.save(buyersusers);
			}
		}
		// 平台
		List<Platformcapitalchanges> platformDatails = platformCapitalChangesRepository.findByAssociateOrderFormId(orderId);
		if (platformDatails != null) {
			List<Platforminformation> platforminformations = platforminformationRepository.findAll();
			if (platforminformations != null && platforminformations.size() > 0) {
				Platforminformation platforminformation = platforminformations.get(0);
				for (Platformcapitalchanges platformDatail : platformDatails) {
					if (platformDatail.getChangeReasonId() == null) {
						continue;
					}
					if (Integer.valueOf(platformDatail.getChangeReasonId()) < 5 || Integer.valueOf(platformDatail.getChangeReasonId()) > 20) {
						continue;
					}
					Platformcapitalchanges changeDetil = copy(platformDatail);
					if (StringUtils.equals(platformDatail.getChangeReasonId(), "9")) {
						// 39 生财账户 减：计算利息的订单本金(产品价格+邮费+补差)
						platforminformation.setBasicAccount(platforminformation.getBasicAccount().subtract(platformDatail.getMoneyAmount()));
						changeDetil.setChangeReasonId("39");
						changeDetil.setChangeBalance(platforminformation.getBasicAccount());
					} else if (StringUtils.equals(platformDatail.getChangeReasonId(), "14")) {
						// 44 基本账户 加：推广费(订单），平台从毛利中减掉
						platforminformation.setBasicAccount(platforminformation.getBasicAccount().add(platformDatail.getMoneyAmount()));
						changeDetil.setChangeReasonId("44");
						changeDetil.setChangeBalance(platforminformation.getBasicAccount());
					} else if (StringUtils.equals(platformDatail.getChangeReasonId(), "18")) {
						// 48 基本账户 加：生财利息（订单中记录的每日利息合计）
						platforminformation.setBasicAccount(platforminformation.getBasicAccount().add(platformDatail.getMoneyAmount()));
						changeDetil.setChangeReasonId("48");
						changeDetil.setChangeBalance(platforminformation.getBasicAccount());
					}
					platforminformationRepository.save(platforminformation);
					platformCapitalChangesRepository.save(changeDetil);
				}
			}
		}
		return new Result<>(true, "撤销订单成功");
	}

	private Platformcapitalchanges copy(Platformcapitalchanges platformDatail) {
		Platformcapitalchanges ret = new Platformcapitalchanges();
		ret.setChangeDate(new Date());
		ret.setChangeNo(platformDatail.getChangeNo());
		ret.setAssociateTaskId(platformDatail.getAssociateTaskId());
		ret.setAssociateOrderFormId(platformDatail.getAssociateOrderFormId());
		ret.setTaskTypeMark(platformDatail.getTaskTypeMark());
		ret.setPaymentsDirection(platformDatail.getPaymentsDirection() == '1' ? '0' : '1');
		ret.setMoneyAmount(platformDatail.getMoneyAmount());
		return ret;
	}

	private Buyercapitalchangesdetails copy(Buyercapitalchangesdetails buyerDatail) {
		Buyercapitalchangesdetails newDatil = new Buyercapitalchangesdetails();
		BuyercapitalchangesdetailsId id = new BuyercapitalchangesdetailsId();
		id.setBuyerUserId(buyerDatail.getId().getBuyerUserId());
		id.setChangeDate(new Date());
		id.setChangeNo(buyerDatail.getId().getChangeNo());
		newDatil.setId(id);
		newDatil.setAssociateTaskId(buyerDatail.getAssociateTaskId());
		newDatil.setAssociateOrderFormId(buyerDatail.getAssociateOrderFormId());
		newDatil.setTaskTypeMark(buyerDatail.getTaskTypeMark());
		newDatil.setChangeAccount(buyerDatail.getChangeAccount());
		newDatil.setPaymentsDirection(buyerDatail.getPaymentsDirection() == '1' ? '0' : '1');
		newDatil.setMoneyAmount(buyerDatail.getMoneyAmount());
		return newDatil;
	}

	private Businesscapitalchangesdetails copy(Businesscapitalchangesdetails businessDetail) {
		Businesscapitalchangesdetails newDatil = new Businesscapitalchangesdetails();
		BusinesscapitalchangesdetailsId id = new BusinesscapitalchangesdetailsId();
		id.setBusinessUserId(businessDetail.getId().getBusinessUserId());
		id.setChangeDate(new Date());
		id.setChangeNo(businessDetail.getId().getChangeNo());
		newDatil.setId(id);
		newDatil.setAssociateTaskId(businessDetail.getAssociateTaskId());
		newDatil.setAssociateOrderFormId(businessDetail.getAssociateOrderFormId());
		newDatil.setTaskTypeMark(businessDetail.getTaskTypeMark());
		newDatil.setChangeAccount(businessDetail.getChangeAccount());
		newDatil.setPaymentsDirection(businessDetail.getPaymentsDirection() == '1' ? '0' : '1');
		newDatil.setMoneyAmount(businessDetail.getMoneyAmount());
		return newDatil;
	}

	public Map<String, List<Ordersstepattach>> getOrdersStepAttachs(String orderid) {
		String sql = "select * from Ordersstepattach t where t.OrderID=:orderid order by t.attachNo";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderid", orderid);
		List<Ordersstepattach> ordersstepattachs = ordersstepattachRepository.queryListBySql(sql, params, Ordersstepattach.class);
		Map<String, List<Ordersstepattach>> map = new HashMap<String, List<Ordersstepattach>>();
		if (ordersstepattachs != null) {
			for (Ordersstepattach ordersstepattach : ordersstepattachs) {
				List<Ordersstepattach> temp = map.get(ordersstepattach.getId().getOrderStepId());
				if (temp == null) {
					temp = new ArrayList<>();
					map.put(ordersstepattach.getId().getOrderStepId(), temp);
				}
				temp.add(ordersstepattach);
			}
		}
		return map;
	}
}
